/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sunspotworld;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

/**
 *
 * @author me
 */
public class RebootCounter {
    private static RebootCounter instance = new RebootCounter();
    private RecordStore rec;
    private RecordEnumeration ren;
    private static final String REC_KEY = "RebootCounter";
    private static int id;
    
    private RebootCounter() {
        try {
            rec = RecordStore.openRecordStore(REC_KEY, true);
            ren = rec.enumerateRecords(null, null, false);
            if (ren.hasNextElement()) {
                id = ren.nextRecordId();
            } else {
                id = rec.addRecord(this.intToByteArray(0), 0, 4);
            }
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        } 
    }
    
    public static RebootCounter getInstance() {
        return instance;
    }
    
    public void reset() {
        try {
            rec.setRecord(id, this.intToByteArray(0), 0, 4);
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
    }
    
    public int getCount() {
        try {
            return byteArrayToInt(rec.getRecord(id));
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
        return -1;
    }

    public void increment() {
        try {
            int count = this.byteArrayToInt(rec.getRecord(id));
            rec.setRecord(id, this.intToByteArray(count+1), 0, 4);
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
    }
    
    protected int byteArrayToInt(byte [] b) {
        return (b[0] << 24)
                + ((b[1] & 0xFF) << 16)
                + ((b[2] & 0xFF) << 8)
                + (b[3] & 0xFF);
    }
    
    protected byte[] intToByteArray(int value) {
        return new byte[] {
                (byte)(value >>> 24),
                (byte)(value >>> 16),
                (byte)(value >>> 8),
                (byte)value};
    }
}
